let app = getApp();
var base64 = require('../../utils/base64.js');
Page({
  /** 
   * 页面的初始数据
   */
  data: {
    glistAll: [],//所购商品信息
    glist: [],
    address: [],//收货地址信息
    active: 'active',
    product_id: '',//购物车id
    shop_id: "",//店铺id
    user_address_default: 0,//是否存在默认地址
    address_id: '',//地址id
    k: '',
    u: '',
    user_address_contact: '',//收货人姓名
    user_address_phone: '',//收货人电话
    user_address_area: '',//收货人地点
    user_address_address: '',//收货人详细地址
    pay_way: 1,//支付方式 1在线支付 2货到付款
    liuyan: "",
    is_show_time: 1,
    hd: 'pay_add',
    count_price: '',//合计金额
    is_add: false,
    is_discount: 0,//否开启会员折扣 1-开启会员折扣 0-关闭会员折扣
    switch1Checked: false,
    voucher_id: [],//店铺代金券
    redpacket_id: 0,//平台红包
    delivery: 'submit',
    disabled:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    new app.ToastPannel();
    var product_id = options.product_id
    var address_id = options.address_id
    if (address_id == undefined) {
      address_id = ''
    }
    var user_address_address = options.user_address_address
    var user_address_area = options.user_address_area
    var user_address_contact = options.user_address_contact
    var user_address_default = options.user_address_default
    var user_address_phone = options.user_address_phone
    if (product_id) {
      wx.setStorage({
        key: 'product',
        data: options.product_id
      })
    } else {
      product_id = wx.getStorageSync('product');
    }

    var k = wx.getStorageSync('key');
    var u = wx.getStorageSync('u');

    wx.request({
      url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=confirm&typ=json',
      method: 'GET',
      data: { k: k, u: u, product_id: product_id, address_id: address_id, ifcart: 1, type_wxapp: 'wxapp' },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var arr = res.data.data.glist
        var total_count = 0;
        var shop_id = [];
        var voucher_id = [];
        var address = res.data.data.address
        var best_voucher = ''
        var glist = res.data.data
        var redpacket_id = 0
        // 有数据的话，就遍历数据，计算总金额 和 总数量  
        if (arr.length > 0) {
          for (var i in arr) {
            var good_num = arr[i].goods;
            arr[i].icon = false
            arr[i].liuyan = ""
            shop_id.push(arr[i].shop_id)
            for (var s in good_num) {
              total_count += Number(good_num[s].sumprice);
              total_count += Number(arr[i].freight)
            }
            //判断优惠券显示
            if (arr[i].best_voucher.length > 0) {
              arr[i].best_voucher_info = '满' + arr[i].best_voucher[0].limit + '减' + arr[i].best_voucher[0].price
            }
            //把所商品的优惠券拼成数组
            if (arr[i].best_voucher.length > 0) {
              voucher_id.push(arr[i].best_voucher[0].id)
            } else {
              voucher_id.push('')
            }

          }

          if (address_id == '' && address.length > 0) {
            for (var j in address) {
              if (address[j].user_address_default == 1) {
                user_address_default = 1
                address_id = address[j].user_address_id
                user_address_contact = address[j].user_address_contact
                user_address_phone = address[j].user_address_phone
                user_address_area = address[j].user_address_area
                user_address_address = address[j].user_address_address

              }
            }
          }
        }
        //判断红包显示
        if (glist.rpt_info && glist.rpt_info.length > 0) {
          glist.best_rpt_info = '满' + glist.rpt_info[0].limit + '减' + glist.rpt_info[0].price
          redpacket_id = glist.rpt_info[0].id
        }
        // 更新数据  
        that.setData({
          glist: glist,
          count_price: glist.order_price.toFixed(2),//注意：该变量报错时改成order_discounted_price，版本差异
          glistAll: arr,
          total: total_count,
          product_id: product_id,
          shop_id: shop_id,
          user_address_default: user_address_default,
          address_id: address_id,
          k: k,
          u: u,
          user_address_contact: user_address_contact,
          user_address_phone: user_address_phone,
          user_address_area: user_address_area,
          user_address_address: user_address_address,
          is_show_time: 0,
          voucher_id: voucher_id,
          is_discount: glist.is_discount,
          redpacket_id: redpacket_id
        });

      }
    })

  },
  //留言
  liuyan: function (e) {
    var that = this
    var arr = that.data.glistAll
    var shop_id = e.target.dataset.id
    for (var i in arr) {
      if (arr[i].shop_id == shop_id) {
        arr[i].liuyan = e.detail.value

        arr[i].icon = true
      }
    }

    this.setData({
      glistAll: arr
    })
  },
  // 清空买家留言内容
  clear: function (e) {
    var that = this
    var arr = that.data.glistAll
    var shop_id = e.target.dataset.shop_id
    for (var i in arr) {
      if (arr[i].shop_id == shop_id) {
        arr[i].liuyan = ""
        arr[i].icon = false
      }
    }
    this.setData({
      glistAll: arr
    })
  },
  //  添加新地址
  add_address: function () {
    wx.redirectTo({

      url: '../address_select/address_select'
    })
  },
  //选择新地址
  address_select: function () {
    wx.redirectTo({

      url: '../address_select/address_select'
    })
  },
  //点击货到付款
  pay_add: function () {
    var that = this
    var freight = 0

    if (that.data.address_id == '') {
      that.show("请选择收货地址")

    } else {

      var that = this
      var arr = that.data.glistAll
      for (var i in arr) {
        freight += Number(arr[i].freight)
      }
      that.setData({
        active: "",
        pay_way: 2,
        freight: freight.toFixed(2)
      })
    }

  },

  //取消
  cancel: function () {
    this.setData({
      active: "active",
      pay_way: 1
    })
  },
  //支付
  formSubmit: function (e) {

    var that = this
    var arr = that.data.glistAll
    var remarks = []
    var pay_way = e.detail.target.dataset.pay_way

    that.setData({
      hd: '',
      delivery: ''
    })


    for (var i in arr) {
      remarks.push(arr[i].liuyan)
    }

    if (that.data.address_id == '') {
      that.show("请选择收货地址")

    } else {
      app.show('订单提交中', 'loading');
      // 获取收货地址数据
      wx.request({
        url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Order&met=addOrder&typ=json&from=wap',
        method: 'GET',
        data: {
          k: that.data.k,
          u: that.data.u,
          address_id: that.data.address_id,
          receiver_name: that.data.user_address_contact,
          receiver_address: that.data.user_address_area + '' + that.data.user_address_address,
          receiver_phone: that.data.user_address_phone,
          cart_id: that.data.product_id.toString(),
          shop_id: that.data.shop_id.toString(),
          pay_way_id: that.data.pay_way,
          remark: remarks.toString(),
          wxapp: 'wxapp',
          is_discount: that.data.is_discount,
          voucher_id: that.data.voucher_id.toString(),
          redpacket_id: that.data.redpacket_id
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          
          if (res.data.status == 200) {

            if (that.data.pay_way == 2) {

              wx.redirectTo({
                url: '../order_list/order_list'
              })
            } else {
              that.pay(res.data.data.uorder)
            }

          } else {
            that.show("支付失败,请重新支付")
          }
        }
      })
    }
  },
  //微信支付接口
  pay: function (uorder_id) {
    var that = this
    var openid = wx.getStorageSync('openid');
    this.setData({disabled:true});
    wx.request({
      url: app.configData.paycenter.api_url + '/index.php?ctl=Pay&met=createWXOrder&typ=json',
      method: 'GET',
      data: {
        k: that.data.k,
        u: that.data.u,
        uorder_id: uorder_id,
        openid: openid,
        trade_type: 'WXAPP'
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res);
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': 'MD5',
          'paySign': res.data.paySign,
          'success': function (res) {
            that.show('支付成功');
            wx.request({
              url: app.configData.paycenter.api_url + '/index.php?ctl=Pay&met=order_status&typ=json',
              method: 'GET',
              data: {
                k: that.data.k,
                u: that.data.u,
                order_id: uorder_id,
                buyer_id: that.data.u,
              },
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
                wx.redirectTo({
                  url: '../order_list/order_list'
                })
              }
            })
          },
          'fail': function (res) {
            wx.redirectTo({
              url: '../order_list/order_list'
            })
          },
          'complete': function (res) {
            wx.redirectTo({
              url: '../order_list/order_list'
            })
          }
        });
      }

    })

  },
  //加价购
  // get_addShop: function (e) {
  //   this.setData({
  //     is_add: true
  //   })
  // },
  off: function () {
    this.setData({
      is_add: false
    })
  },
  //代金券领取
  receive: function (e) {
    var that = this
    var shop_id = e.target.dataset.shop_id

  },
  //跳转到代金券页面
  store_voucher_get: function (e) {
    var that = this
    var glist = encodeURIComponent(base64.encode(JSON.stringify(e.currentTarget.dataset.info)))
    var v_price = e.currentTarget.dataset.best_voucher_price
    var shop_id = e.currentTarget.dataset.shop_id
    var voucher_ids = e.currentTarget.dataset.voucher_ids
    var keys = e.currentTarget.dataset.keys
    wx.navigateTo({
      url: '../store_voucher_get/store_voucher_get?glist=' + glist + '&count_price=' + that.data.count_price + '&v_price=' + v_price + '&shop_id=' + shop_id + '&voucher_ids=' + voucher_ids + '&keys=' + keys,
    })
  },
  //会员折扣切换
  switch1Change: function () {
    var that = this
    if (that.data.is_discount == 0) {
      wx.request({
        url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=confirm&typ=json',
        method: 'GET',
        data: { k: that.data.k, u: that.data.u, product_id: that.data.product_id, address_id: that.data.address_id, ifcart: 1, type_wxapp: 'wxapp', is_discount: 1 },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          var arr = res.data.data.glist
          var total_count = 0;
          var shop_id = [];
          var glist = res.data.data

          // 有数据的话，就遍历数据，计算总金额 和 总数量  
          if (arr.length > 0) {
            for (var i in arr) {
              var good_num = arr[i].goods;
              arr[i].icon = false
              arr[i].liuyan = ""
              shop_id.push(arr[i].shop_id)
              for (var s in good_num) {
                total_count += Number(good_num[s].sumprice);
                total_count += Number(arr[i].freight)
              }
            }
          }
          // 更新数据  
          that.setData({
            glist: glist,
            count_price: glist.order_price.toFixed(2),//注意：该变量报错时改成order_discounted_price，版本差异
            glistAll: arr,
            total: total_count,
            is_show_time: 0,
            voucher_id: [],
            is_discount: 1,
            switch1Checked: true,
            redpacket_id: 0
          });
        }
      })

    } else {

      wx.request({
        url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=confirm&typ=json',
        method: 'GET',
        data: { k: that.data.k, u: that.data.u, product_id: that.data.product_id, address_id: that.data.address_id, ifcart: 1, type_wxapp: 'wxapp', is_discount: 0 },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          var arr = res.data.data.glist
          var total_count = 0;
          var shop_id = [];
          var voucher_id = [];
          var address = res.data.data.address
          var best_voucher = ''
          var glist = res.data.data
          var redpacket_id = 0
          // 有数据的话，就遍历数据，计算总金额 和 总数量  
          if (arr.length > 0) {
            for (var i in arr) {
              var good_num = arr[i].goods;
              arr[i].icon = false
              arr[i].liuyan = ""
              shop_id.push(arr[i].shop_id)
              for (var s in good_num) {
                total_count += Number(good_num[s].sumprice);
                total_count += Number(arr[i].freight)
              }
              //判断优惠券显示
              if (arr[i].best_voucher.length > 0) {
                arr[i].best_voucher_info = '满' + arr[i].best_voucher[0].limit + '减' + arr[i].best_voucher[0].price
              }
              //把所商品的优惠券拼成数组
              if (arr[i].best_voucher.length > 0) {
                voucher_id.push(arr[i].best_voucher[0].id)
              } else {
                voucher_id.push('')
              }

            }
          }
          //判断红包显示
          if (glist.rpt_info && glist.rpt_info.length > 0) {
            glist.best_rpt_info = '满' + glist.rpt_info[0].limit + '减' + glist.rpt_info[0].price
            redpacket_id = glist.rpt_info[0].id
          }
          // 更新数据  
          that.setData({
            glist: glist,
            count_price: glist.order_price.toFixed(2),//注意：该变量报错时改成order_discounted_price，版本差异
            glistAll: arr,
            total: total_count,
            shop_id: shop_id,
            voucher_id: voucher_id,
            redpacket_id: redpacket_id,
            switch1Checked: false,
            is_discount: 0
          });

        }
      })
    }
  },
  //跳转到平台红包页面
  red_packet: function (e) {
    var that = this
    var glist = encodeURIComponent(base64.encode(JSON.stringify(that.data.glist)))
    var redpacket_price = e.currentTarget.dataset.redpacket_price
    var redpacket_limit = e.currentTarget.dataset.redpacket_limit
    var redpacket_id = e.currentTarget.dataset.redpacket_id
    wx.navigateTo({
      url: '../red_packet_get/red_packet_get?redpacket_price=' + redpacket_price + '&redpacket_limit=' + redpacket_limit + '&redpacket_id=' + redpacket_id + '&glist=' + glist + '&count_price=' + that.data.count_price,
    })
  }

})